import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:riverpod_t/base/base_consumer_widget.dart';
import 'package:riverpod_t/base/base_list_view.dart';
import 'package:riverpod_t/base/base_stateful_page.dart';
import 'package:riverpod_t/base/empty_widget.dart';
import 'package:riverpod_t/page/car/data/model/info_model.dart';
import 'package:riverpod_t/page/car/river/car_list_river.dart';
import 'package:riverpod_t/page/car/router/car_router.dart';
import 'package:riverpod_t/page/car/state/car_state.dart';
import 'package:riverpod_t/page/car/widget/car_info_item.dart';
import 'package:riverpod_t/until/app_util.dart';

class CarPage extends BasePage {
  const CarPage({super.key});

  @override
  BasePageState<BasePage> getState() => _CarPageState();
}

class _CarPageState extends BasePageState<CarPage> {
  /// 列表控制器
  final ScrollController scrollController = ScrollController();

  /// 刷新组建控制器
  final RefreshController refreshController = RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    super.appBarTitle = '列表二';
    allowBackNavigation = false;
  }

  @override
  Widget buildLeftButton() {
    return const SizedBox();
  }

  Widget _listBody(BuildContext context, CarState state, WidgetRef ref) {
    if (AppUtil.isEmpty(state.list)) return EmptyWidget();
    ref.listen(carListRiverProvider, (p, n) => _listenOpChange(p, n));
    return BaseListView(
      refreshController: refreshController,
      scrollController: scrollController,
      backgroundColor: const Color(0xFFF3F4F8),
      enablePullDown: true,
      enablePullUp: true,
      data: state.list,
      onRefresh: () => ref.read(carListRiverProvider.notifier).refresh(isRefresh: true),
      onLoading: () => ref.read(carListRiverProvider.notifier).refresh(),
      itemBuilder: (InfoModel model, int index) {
        return CarInfoWidget(
          model: model,
          onTap: () {
            CarNavigator.toCarDetailPage(context, entityId: model.id);
          },
        );
      },
    );
  }

  void _listenOpChange(AsyncValue<CarState?>? previous, AsyncValue<CarState?> next) {
    refreshController.refreshCompleted();
    refreshController.loadComplete();
    if (next.value?.hasNext == false) {
      refreshController.loadNoData();
    }
  }

  @override
  Widget buildPage(BuildContext context) {
    return BaseConsumerWidget<CarState>(
      provider: carListRiverProvider,
      builder: (context, state, ref) => _listBody(context, state, ref),
    );
  }
}
